package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.CompanyDao;
import com.cn.wanxi.dao.NavDao;
import com.cn.wanxi.dao.impl.CompanyImpl;
import com.cn.wanxi.dao.impl.NavImpl;
import com.cn.wanxi.model.CompanyModel;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.service.NavService;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

public class NavServiceRedisImpl implements NavService {
    @Override
    public List<NavModel> getNavList() {
        List<NavModel> list = new ArrayList<>();
        Jedis jedis = new Jedis();
        boolean isRedis = jedis.exists("href");
        long length = jedis.llen("href");//拿到集合的长度
        if (isRedis) {
            List<String> hrefList = jedis.lrange("href", 0, length);
            List<String> titleList = jedis.lrange("title", 0, -1);
            for (int i = 0; i < length; i++
            ) {
                NavModel model = new NavModel();
                model.setTitle(titleList.get(i));
                model.setHref(hrefList.get(i));
                list.add(model);
            }
            System.out.println("redis");
        } else {
            NavDao navDao = new NavImpl();
            list = navDao.getNavList();
            for (NavModel model : list
            ) {
                jedis.rpush("href", model.getHref());
                jedis.rpush("title", model.getTitle());
            }

            System.out.println("mysql");
        }


        return list;
    }

    public String add(NavModel model) {
        Jedis jedis = new Jedis();
        NavDao navDao = new NavImpl();
        int result = navDao.add(model);
        if (result > 0) {
//            jedis.flushDB();
//            jedis.flushAll();
            jedis.del("href", "title");
        }
        return result > 0 ? "success" : "error";
    }
}
